package com.qf.face.client.utils;

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 30909
 * 网络请求的工具类  这里有个重点是加载
 */
public class OkHttpUtil {
    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

//    private static OKHttpUtil instance;
//
//    public static final byte [] LOCKER=new byte [0];
//
//    public static OKHttpUtil getInstance(){
//        if(instance==null){
//            synchronized (LOCKER){
//                if(instance==null){
//                    instance=new OKHttpUtil();
//                }
//            }
//        }
//        return instance;
//    }

    private OkHttpClient okHttpClient;

    private OkHttpUtil(){
        okHttpClient=new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .build();
    }

    private static class Holder{
        static OkHttpUtil instance=new OkHttpUtil();
    }

    public static OkHttpUtil getInstance(){
        return Holder.instance;
    }

    public String post(String url,String json){
        //实例化请求报文
        RequestBody body=RequestBody.create(MEDIA_TYPE_JSON,json);
        //构建请求对象
        Request.Builder builder=new Request.Builder()
                .url(url).addHeader("client-type","oa-sign")
                .post(body);
        Request request=builder.build();

        try {
            //请求网络
            Response response = okHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
